extends Node

## websocket 地址
const websocket_url : String = "ws://121.36.37.16:8002/game"
## websocket 实例
var socket : WebSocketPeer
## 是否已连接
var connected : bool  = false

func _ready() -> void:
	socket = WebSocketPeer.new()
	set_process(false)
	pass

func _process(_delta: float) -> void:
	socket.poll()
	var state = socket.get_ready_state()
	if state == WebSocketPeer.STATE_OPEN:
		if !connected : 
			connected = true
			print("WebSocket已连接")
		while socket.get_available_packet_count():
			return socket.get_packet().get_string_from_utf8()
	elif state == WebSocketPeer.STATE_CLOSING:
		print("WebSocket正在关闭连接")
		pass
	elif state == WebSocketPeer.STATE_CLOSED:
		print("WebSocket已关闭")
		connected = false
		set_process(false)
		return
	pass

# 结束时关闭连接
func _exit_tree() -> void:
	socket.close()
	connected =false

## 开始连接
func connect_server():
	var err = socket.connect_to_url(websocket_url + "?username=" + Library_Tool.get_device_id())
	print("WebSocket开始连接")
	if err != OK:
		print("WebSocket连接失败,关闭连接")
		set_process(false)
	else :
		set_process(true)
	return

## 发送消息
func send_message(message: Dictionary):
	var eventJsonString = JSON.stringify(message);
	socket.send_text(eventJsonString)
